package cn.javabb.core.service.biz;

import cn.javabb.common.exception.BusinessException;
import cn.javabb.core.annotation.RedisCache;
import cn.javabb.core.base.BaseService;
import cn.javabb.core.constant.BizConstant;
import cn.javabb.core.entity.biz.PostHideDO;
import cn.javabb.core.entity.biz.CommentDO;
import cn.javabb.core.entity.biz.UserHideContentDO;
import cn.javabb.core.entity.sys.UserDO;
import cn.javabb.core.service.sys.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * @Author QINB imqinbao@163.com
 * @CreateDate 2019/2/21/021 18:16
 * @Since V1.0
 */
@Service
public class PostHideService extends BaseService<PostHideDO> {

    @Autowired
    UserService userService;
    @Autowired
    CommentService commentService;
    @Autowired
    UserHideContentService userHideContentService;

    public boolean buyHideContentEnable(Integer hideContentId,Integer loginUserId){
        PostHideDO hideContent = this.queryById(hideContentId);
        UserDO user = userService.queryById(loginUserId);
        if(null != user.getMoney() && user.getMoney()>=hideContent.getPrice()){
            return true;
        }
        return false;
    }

    /**
     * 购买隐藏内容
     * @param loginUserId
     * @param hideContentId
     * @return
     */

    @RedisCache(flush = true)
    public boolean buyHideContent(Integer hideContentId,Integer loginUserId){

        PostHideDO hideContent = this.queryById(hideContentId);
        UserDO userDO = userService.queryById(loginUserId);
        userDO.setMoney(userDO.getMoney()-hideContent.getPrice());
        if(userService.updateSelective(userDO)<0){
            return false;
        }
        UserHideContentDO userHideContentDO = new UserHideContentDO();
        userHideContentDO.setHideContentId(hideContentId).setUserId(loginUserId);
        if(userHideContentService.insert(userHideContentDO)>0){
            //购买成功
            //插入一条评论记录
            CommentDO comment = new CommentDO();
            comment.setArticleId(hideContent.getPostId());
            comment.setCommentApproved(1);
            comment.setArticleType(BizConstant.ARTICLE_TYPE_POST);
            comment.setUserId(loginUserId);
            comment.setCommentContent("购买了付费内容");
            comment.setParentId(-1);
            if(commentService.insertSelective(comment)<0){
                throw new BusinessException(loginUserId+"购买付费内容"+hideContentId+"=>添加评论内容失败");
            }
            return true;
        }
        return false;
    }
}
